const fs = require("fs");
const path = require("path");
const marked = require("marked");
const browserSync = require("browser-sync");

const mdPath = path.join(__dirname, process.argv[2]);
const cssPath = path.resolve("github.css");
const htmlPath = mdPath.replace(path.extname(mdPath), ".html");

browserSync.init({
  browser: "", // 使用默认浏览器
  server: __dirname, // 主目录
  watch: true, // 热更新
  index: path.basename(htmlPath), // 主页
});

fs.watchFile(mdPath, { interval: 20 }, (curr, prev) => {
  if (curr.mtime !== prev.mtime) {
    fs.readFile(mdPath, "utf-8", (err, data) => {
      let htmlStr = marked(data);
      fs.readFile(cssPath, "utf-8", (err, data) => {
        let rethtml = temp
          .replace("{{content}}", htmlStr)
          .replace("{{style}}", data);

        // 将上述内容写入到html文件中
        fs.writeFile(htmlPath, rethtml, (err) => {
          if (err) {
            return console.log(err);
          }

          console.log("写入成功");
        });
      });
    });
  }
});

const temp = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .markdown-body {
                box-sizing: border-box;
                min-width: 200px;
                max-width: 1000px;
                margin: 0 auto;
                padding: 45px;
            }
            @media (max-width: 750px) {
                .markdown-body {
                    padding: 15px;
                }
            }
            {{style}}
        </style>
    </head>
    <body>
        <div class="markdown-body">
            {{content}}
        </div>
    </body>
    </html>
`;
